package com.rc.saas.tenant.service.enterprise;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rc.saas.tenant.common.utils.MD5Utils;
import com.rc.saas.tenant.common.utils.RestTemplateUtil;
import com.rc.saas.tenant.common.vo.TResponse;
import com.rc.saas.tenant.mapper.enterprise.EnterpriseSubmemberApplyMapper;
import com.rc.saas.tenant.mapper.enterprise.EnterpriseSubmemberMapper;
import com.rc.saas.tenant.mapper.enterprise.EnterpriseSubmemberRecordMapper;
import com.rc.saas.tenant.mapper.member.RcMemberFlagMapper;
import com.rc.saas.tenant.model.enterprise.*;
import com.rc.saas.tenant.model.member.MemberInfo;
import com.rc.saas.tenant.model.member.RcMemberFlag;
import com.rc.saas.tenant.model.member.RcMemberFlagExample;
import com.rc.saas.tenant.model.tenant.Tenant;
import com.rc.saas.tenant.model.tenant.TenantUser;
import com.rc.saas.tenant.search.enterprise.EnterpriseSubMemberApplySearch;
import com.rc.saas.tenant.service.member.MemberInfoService;
import com.rc.saas.tenant.service.member.RcMemberFlagService;
import com.rc.saas.tenant.service.tenant.TenantUserService;
import com.rc.saas.tenant.vo.enterprise.EnterpriseSubMemberApplyResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @author frog
 * @date 2021/2/7
 */
@Service
public class EnterpriseSubmemberApplyServiceImpl implements EnterpriseSubmemberApplyService {

    @Autowired
    private EnterpriseSubmemberApplyMapper enterpriseSubmemberApplyMapper;

    @Autowired
    private MemberInfoService memberInfoService;

    @Autowired
    private EnterpriseMemberService enterpriseMemberService;

    @Autowired
    private EnterpriseSubmemberRecordMapper enterpriseSubmemberRecordMapper;

    @Autowired
    private EnterpriseSubmemberMapper enterpriseSubmemberMapper;

    @Autowired
    private TenantUserService tenantUserService;

    @Autowired
    private RestTemplate hcRestTemplate;

    @Autowired
    private RcMemberFlagMapper memberFlagMapper;

    @Override
    public EnterpriseSubmemberApplyMapper getMapper() {
        return enterpriseSubmemberApplyMapper;
    }

    @Override
    public PageInfo<EnterpriseSubMemberApplyResult> listPageEntSubmember(EnterpriseSubMemberApplySearch search) {
        PageHelper.startPage(search.getOffset(), search.getLimit());
        List<EnterpriseSubMemberApplyResult> list = enterpriseSubmemberApplyMapper.listSubmemberApply(search);
        list.stream().filter(apply -> "1".equals(apply.getStatus())).forEach(passedApply -> {
            TenantUser tenantUser = tenantUserService.selectByMobile(passedApply.getPhone());
            if (tenantUser != null && "0".equals(tenantUser.getStatus())) {
                passedApply.setExistUser(true);
            }
        });

        return new PageInfo<>(list);
    }

    @Override
    public TResponse saveApplyRecord(EnterpriseSubmemberApply enterpriseSubmemberApply, TenantUser user) {

        if ("0".equals(enterpriseSubmemberApply.getStatus())) {
            TResponse tResponse = new TResponse();
            tResponse.setStatus(600);
            tResponse.setMessage("没有进行审核");
            return tResponse;
        }

        MemberInfo submember = memberInfoService.selectByPrimaryKey(enterpriseSubmemberApply.getSubMemberId());
        EnterpriseMember enterpriseMember = enterpriseMemberService.selectMemberByMobile(enterpriseSubmemberApply.getTenantCode(), enterpriseSubmemberApply.getEnterpriseMobile());
        if (enterpriseMember == null) {
            return TResponse.FAIL("不存在此企业会员");
        }
        if (submember == null) {
            return TResponse.FAIL("所申请会员手机号有误");
        }
        //审核状态 0未审核，1审核通过，2审核不通过 默认0
        if ("2".equals(enterpriseSubmemberApply.getStatus())) {
            enterpriseSubmemberApply.setStatus("2");
            enterpriseSubmemberApplyMapper.updateByPrimaryKeySelective(enterpriseSubmemberApply);
            return TResponse.SUCCESS();
        }

        if ("1".equals(enterpriseSubmemberApply.getStatus())) {
            Date date = new Date();

            enterpriseSubmemberApply.setStatus("1");
            enterpriseSubmemberApplyMapper.updateByPrimaryKeySelective(enterpriseSubmemberApply);

            EnterpriseSubmemberRecord enterpriseSubmemberRecord = new EnterpriseSubmemberRecord();
            enterpriseSubmemberRecord.setEnterpriseId(enterpriseMember.getEnterpriseId());
            enterpriseSubmemberRecord.setEnterpriseMemberId(enterpriseMember.getMemberId());
            enterpriseSubmemberRecord.setSubMemberId(submember.getMemberId());
            enterpriseSubmemberRecord.setTenantCode(enterpriseSubmemberApply.getTenantCode());
            enterpriseSubmemberRecord.setRecordType(enterpriseSubmemberApply.getApplyType());
            enterpriseSubmemberRecord.setLastUpdatedBy(user.getLoginName());
            enterpriseSubmemberRecord.setLastUpdatedTime(date);
            enterpriseSubmemberRecordMapper.insertSelective(enterpriseSubmemberRecord);

            EnterpriseSubmember enterpriseSubmember = new EnterpriseSubmember();
            enterpriseSubmember.setMemberId(submember.getMemberId());
            enterpriseSubmember.setBelongEnterpriseId(enterpriseMember.getEnterpriseId());
            enterpriseSubmember.setTenantCode(enterpriseSubmemberApply.getTenantCode());
            //状态(0正常 1停用) 默认 0
            enterpriseSubmember.setStatus("0");
            enterpriseSubmember.setLastUpdatedBy(user.getLoginName());
            enterpriseSubmember.setLastUpdatedTime(date);
            enterpriseSubmemberMapper.insertSelective(enterpriseSubmember);

            submember.setEnterpriseMemberId(enterpriseMember.getMemberId());
            submember.setBelongEnterpriseId(enterpriseMember.getEnterpriseId());
            //会员类型(0个人 1企业主帐户 2企业子帐户 3互联互通用户) 默认0
            submember.setMemberType("2");
            memberInfoService.updateByPrimaryKeySelective(submember);
            return TResponse.SUCCESS();
        }
        return TResponse.SUCCESS();
    }

    @Override
    public void updateSubmemberApplyForAudit(Long id, String status, String reason) {
        EnterpriseSubmemberApply apply = enterpriseSubmemberApplyMapper.selectByPrimaryKey(id);


        if ("1".equals(status)) {


            enterpriseSubmemberApplyMapper.updateEnterpriseId();


            if ("1".equals(apply.getHasPermission())) {
                TenantUser user = tenantUserService.selectByMobile(apply.getPhone());
                if (user == null) {
                    user = new TenantUser();
                    user.setEnterpriseId(apply.getEnterpriseId());
                    user.setUserType("20");
                    user.setLoginName(apply.getPhone());

                    String saltPassword = MD5Utils.encrypt(user.getLoginName(), user.getLoginName());
                    user.setPassword(saltPassword);
                    user.setMobile(apply.getPhone());
                    user.setUserSex(apply.getSex());
                    user.setCitizenshipNumber(apply.getCitizenshipNumber());
                    tenantUserService.insertSelective(user);
                }
            }

            String url = "https://charge.ruishangkj.com/rc-mini/user/open/webLoginByAuthCode?authCode=56789&mobile=";
            url = url + apply.getPhone();
            //创建请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<String> requestEntity = new HttpEntity<String>(headers);
            //返回字符串
            ResponseEntity<String> response = hcRestTemplate.postForEntity(url, requestEntity, String.class);
            String body = response.getBody();
            HashMap map = JSON.parseObject(body, HashMap.class);

            Long memberId = null;
            if ((int)map.get("status") == 200) {
                JSONObject jsonObject = (JSONObject) map.get("data");
                memberId = Integer.toUnsignedLong((Integer) jsonObject.get("memberId"));

                MemberInfo memberInfo = memberInfoService.selectByPrimaryKey(memberId);
                if (memberInfo != null) {
                    memberInfo.setNickname(apply.getNickname());
                    memberInfo.setSex(apply.getSex());
                    memberInfo.setBirthday(apply.getBirthday());
                    memberInfo.setAddress(apply.getAddress());
                    memberInfo.setRecommenderId(apply.getRecommenderId());
                    memberInfoService.updateByPrimaryKeySelective(memberInfo);
                }
            }

            if (memberId != null) {


                RcMemberFlag flag = new RcMemberFlag();
                flag.setEnterpriseId(apply.getEnterpriseId());
                flag.setIsEnterpriseLevel("1");
                RcMemberFlagExample example = new RcMemberFlagExample();
                example.createCriteria().andMemberIdEqualTo(memberId);
                memberFlagMapper.updateByExampleSelective(flag, example);
            }

            if (apply.getMemberId() == null) {
                apply.setMemberId(memberId);
            }
        }

        apply.setApplyStatus(status);
        apply.setReason(reason);
        enterpriseSubmemberApplyMapper.updateByPrimaryKeySelective(apply);
    }

    @Override
    public void deleteSubmemberApply(Long id) {
        EnterpriseSubmemberApply apply = enterpriseSubmemberApplyMapper.selectByPrimaryKey(id);

        if ("1".equals(apply.getApplyStatus())) {
            EnterpriseSubmember submember = enterpriseSubmemberMapper.selectMemberByMemberId(apply.getSubMemberId());
            if (submember != null) {
                enterpriseSubmemberMapper.deleteByPrimaryKey(submember.getMemberId());
            }
            TenantUser exitUser = tenantUserService.selectUserByMobile(apply.getEnterpriseId(), apply.getPhone());
            if (exitUser != null) {
                tenantUserService.deleteByPrimaryKey(exitUser.getTenantUserId());
            }
        }
        enterpriseSubmemberApplyMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void updateSubmemberApply(EnterpriseSubmemberApply enterpriseSubmemberApply) {
        if (enterpriseSubmemberApply.getEnterpriseId() != null) {
            if (enterpriseSubmemberApply.getEnterpriseName() == null) {
                EnterpriseMember enterprise = enterpriseMemberService.selectByPrimaryKey(enterpriseSubmemberApply.getEnterpriseId());
                enterpriseSubmemberApply.setEnterpriseName(enterprise.getEnterpriseName());
                enterpriseSubmemberApply.setEnterpriseOwner(enterprise.getEnterpriseOwner());
                enterpriseSubmemberApply.setOwnerMobile(enterprise.getOwnerMobile());
                enterpriseSubmemberApply.setContactName(enterprise.getContactName());
            }

        }

        enterpriseSubmemberApplyMapper.updateByPrimaryKeySelective(enterpriseSubmemberApply);
        if ("1".equals(enterpriseSubmemberApply.getApplyStatus())) {
            TenantUser user = tenantUserService.selectByMobile(enterpriseSubmemberApply.getPhone());

            if ("1".equals(enterpriseSubmemberApply.getHasPermission())) {
                if (user == null) {
                    user = new TenantUser();
                    user.setEnterpriseId(enterpriseSubmemberApply.getEnterpriseId());
                    user.setUserType("20");
                    user.setLoginName(enterpriseSubmemberApply.getPhone());

                    String saltPassword = MD5Utils.encrypt(user.getLoginName(), user.getLoginName());
                    user.setPassword(saltPassword);
                    user.setMobile(enterpriseSubmemberApply.getPhone());
                    user.setUserSex(enterpriseSubmemberApply.getSex());
                    user.setCitizenshipNumber(enterpriseSubmemberApply.getCitizenshipNumber());
                    tenantUserService.insertSelective(user);
                }
            } else {
                if ("0".equals(enterpriseSubmemberApply.getHasPermission())) {
                    if (user != null) {
                        user.setStatus("1");
                        tenantUserService.updateByPrimaryKeySelective(user);
                    }
                }
            }
            String url = "https://charge.ruishangkj.com/rc-mini/user/open/webLoginByAuthCode?authCode=56789&mobile=";
            url = url + enterpriseSubmemberApply.getPhone();
            //创建请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<String> requestEntity = new HttpEntity<String>(headers);
            //返回字符串
            ResponseEntity<String> response = hcRestTemplate.postForEntity(url, requestEntity, String.class);
            String body = response.getBody();
            HashMap map = JSON.parseObject(body, HashMap.class);
            if ((int)map.get("status") == 200) {
                JSONObject jsonObject = (JSONObject) map.get("data");
                Long memberId = Integer.toUnsignedLong((Integer) jsonObject.get("memberId"));

                MemberInfo memberInfo = memberInfoService.selectByPrimaryKey(memberId);
                if (memberInfo != null) {
                    memberInfo.setNickname(enterpriseSubmemberApply.getNickname());
                    memberInfo.setSex(enterpriseSubmemberApply.getSex());
                    memberInfo.setBirthday(enterpriseSubmemberApply.getBirthday());
                    memberInfo.setAddress(enterpriseSubmemberApply.getAddress());
                    memberInfo.setRecommenderId(enterpriseSubmemberApply.getRecommenderId());
                    memberInfoService.updateByPrimaryKeySelective(memberInfo);

                }
            }

        }

    }

    @Override
    public EnterpriseSubmemberApply selectByMember(Long memberId) {
        EnterpriseSubmemberApplyExample example = new EnterpriseSubmemberApplyExample();
        example.createCriteria().andMemberIdEqualTo(memberId);
        return enterpriseSubmemberApplyMapper.selectByExample(example).stream().findFirst().orElseGet(() -> null);
    }

    @Override
    public void insertReturnId(EnterpriseSubmemberApply enterpriseSubmemberApply) {
        enterpriseSubmemberApplyMapper.insertReturnId(enterpriseSubmemberApply);
    }
}
